;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.GiftOrder", [])
        .controller("GiftOrderCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "EventBus", "$filter", "UserContextService", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, EventBus, $filter, UserContextService, $stateParams) {
            $scope.activeFlag = [true, false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.machineNoList = [];
            $scope.submitEnum = {
                Save: 0,
                Submit: 1
            };

            $scope.costPriceShow = false;

            $scope.tabFlag = {};
            var tabFlag = {
                0: "详情",
                1: "新增",
                2: "编辑",
                3: "详情",
            };

            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/salesBill/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/salesBill/exportAll")
            };
            $scope.orderObj = {
                details: []
            };
            $scope.tableConfig = {
                fixedWidth: 150,
                scrollWidth: 1400,
                tableCol: [{
                        type: "",
                        name: "兑换订单号",
                        dataField: "exchangeNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "customerName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "手机号",
                        dataField: "customerPhoneNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "机型",
                        dataField: "machineType",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "车号",
                        dataField: "vinCode",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createTimeStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建出库单状态",
                        dataField: "createOutboundStatusStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outboundStatusStr",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 110,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.outboundStatus = [
                {id: 0, name: "未出库"},
                {id: 1, name: "部分出库"},
                {id: 2, name: "已出库"}
            ];
            $scope.createOutboundStatus = [
                {id: 0, name: "未创建"},
                {id: 1, name: "进行中"},
                {id: 2, name: "已完成"}
            ];

            $scope.materielTableConfig = {
                scrollWidth: 1400,
                tableCol: [{
                        name: "零件编号",
                        width: 140,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDesc",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 80,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "申请数量",
                        width: 80,
                        dataField: "applyQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: "price"
                    },
                    {
                        name: "申请总价",
                        width: 100,
                        dataField: "applyTotalAmount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "创建出库单数量",
                        width: 130,
                        dataField: "createOutboundQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "实际出库数量",
                        width: 130,
                        dataField: "actualOutboundQty",
                        input: false,
                        inputType: ""
                    },
                ]
            };

            var btnPermissionCode = {
                giftOrderAdd: window.ActionCode.giftOrderAdd,
                giftOrderEdit: window.ActionCode.giftOrderEdit,
                giftOrderDel: window.ActionCode.giftOrderDel,
            };

            $scope.btnPermission = {
                giftOrderAdd: true,
                giftOrderEdit: true,
                giftOrderDel: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };

            $scope.datePickerFlag = [false, false];
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };


            function initData() {
                $scope.tabFlag = {};
                $scope.orderObj = {
                    // headerInfo: {},
                    details: []
                };
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/giftticket/exchange/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = $scope.condition;
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createTimeStr = $filter("YbDate")(item.createTimeStr, 'yyyy-MM-dd HH:mm:ss');
                        item.createOutboundStatusStr = $filter("CreateOutboundStatus")(item.createOutboundStatus);
                        item.outboundStatusStr = $filter("OutboundStatus")(item.outboundStatus);
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list;
                });
            }

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };


            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.orderObj.details = data.details;
                    $scope.changeTab(3);
                });
            }

            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/giftticket/exchange/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    setMaterialDesc();
                    return resp.value;
                });
            }

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.details.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.details.length; i < len; i++) {
                    if (!!$scope.orderObj.details[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.details.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.details[i].isChecked) {
                            $scope.orderObj.details.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.details.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.batchDel = function () {
                var deleteList = [];
                angular.forEach($scope.dataList, function (item) {
                    if (item.isChecked) {
                        deleteList.push(item.id);
                    }
                });
                if (deleteList.length === 0) {
                    ybWidget.ShowMessage('请选择可删除数据', MESG_TYPE.Error);
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/giftticket/exchange/delete";
                    ybHttp.Post(service, reqUrl, deleteList).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };
            $scope.delApply = function (id) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/giftticket/exchange/delete";
                    ybHttp.Post(service, reqUrl, [id]).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.changeTab(2);
            };


            $scope.checkDate = function (item, start, end) {
                if ((angular.isUndefined(item[start]) || !item[start]) && (angular.isUndefined(item[end]) || !item[end])) {
                    return;
                }
                if (!!item[start] && (angular.isUndefined(item[end]) || !item[end])) {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    return;
                }
                if ((angular.isUndefined(item[start]) || !item[start]) && !!item[end]) {
                    item[end] = ybWidget.FormatEndDate(item[end]);
                    return;
                }
                var tmpTime = item[start];
                if (item[end] < item[start]) {
                    item[start] = ybWidget.FormatStartDate(item[end]);
                    item[end] = ybWidget.FormatEndDate(tmpTime);
                } else {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    item[end] = ybWidget.FormatEndDate(item[end]);
                }
            };


            $scope.editApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 2;
                    $scope.tabFlag.name = tabFlag[2];
                    $scope.orderObj = data;
                    $scope.orderObj.details = data.details;
                    $scope.orderObj.id = item.id;
                    $scope.changeTab(2);
                });
            };



            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/giftticket/exchange/material/template",
                    importReqService: "device",
                    importReqUrl: "/giftticket/exchange/material/import",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.orderObj.details = [];
                    $scope.orderObj.details = angular.copy(data);
                    $scope.orderObj.totalAmount = 0;
                    angular.forEach($scope.orderObj.details, function (item) {
                        item.materialDes = item.materialsDesc;
                        item.applyQty = item.purchaseQty;
                        item.applyTotalAmount = item.totalPrice;
                    });
                });
            };

            // 选中的零件变化后的回调
            $scope.$watch('orderObj.details.length', function () {
                setMaterialDesc(); 
            });

            function setMaterialDesc() {
                $scope.orderObj.totalAmount = 0;
                angular.forEach($scope.orderObj.details, function (item) {
                    item.materialNo = item.materialsNo ? item.materialsNo : item.materialNo;
                    item.materialsDesc = item.materialsDes ? item.materialsDes : item.materialsDesc;
                    item.applyTotalAmount = $filter("decimalCover")(ybWidget.Times(item.price, item.applyQty), 2);
                    if (item.applyTotalAmount) {
                        $scope.orderObj.totalAmount = ybWidget.MultiPlus(item.applyTotalAmount, $scope.orderObj.totalAmount);
                    }
                });
            }

            $scope.saveData = function (invalid, statues) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = true;
                var service = "device";
                var reqUrl = "/giftticket/exchange/create";
                if ($scope.tabFlag.type == 2) {
                    reqUrl = '/giftticket/exchange/update'
                }
                for (var i = 0, len = $scope.orderObj.details.length; i < len; i++) {
                    $scope.orderObj.details[i].qtyErr = false;
                    if (!$scope.orderObj.details[i].applyQty || parseFloat($scope.orderObj.details[i].applyQty) <= 0) {
                        $scope.orderObj.details[i].qtyErr = true;
                        listValid = false;
                        break;
                    }
                }
                if (!listValid) {
                    return;
                }
                if ($scope.orderObj.details.length === 0) {
                    ybWidget.ShowMessage("零件不可为空", MESG_TYPE.Error);
                    return;
                }
                var param = angular.copy($scope.orderObj);
                param.status = statues;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };


            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            // 修改申请数量
            $scope.setNum = function (item, colItem) {
                item.numErr = false;
                if (item.applyQty > 99999999) {
                    item.applyQty = 99999999;
                    item.applyTotalAmount = $filter("decimalCover")(ybWidget.Times(item.price, item.applyQty), 2);
                    $scope.orderObj.totalAmount = 0;
                    $scope.orderObj.details.forEach(function (item) {
                        if (item.applyTotalAmount) {
                            $scope.orderObj.totalAmount = ybWidget.MultiPlus(item.applyTotalAmount, $scope.orderObj.totalAmount);
                        }
                    })
                }
                if (angular.isUndefined(item[colItem]) || item[colItem] === "") {
                    item.applyTotalAmount = ""
                    item.numErr = true;
                } else {
                    item.applyTotalAmount = $filter("decimalCover")(ybWidget.Times(item.price, item.applyQty), 2);
                    $scope.orderObj.totalAmount = 0;
                    $scope.orderObj.details.forEach(function (item) {
                        if (item.applyTotalAmount) {
                            $scope.orderObj.totalAmount = ybWidget.MultiPlus(item.applyTotalAmount, $scope.orderObj.totalAmount);
                        }
                    })
                }
            };

            (function () {
                var giftItemStr = window.sessionStorage.getItem("giftItem");
                if (!!giftItemStr) {
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.changeTab(2);
                    var giftInfo = JSON.parse(giftItemStr);
                    $scope.orderObj = giftInfo;
                    $scope.orderObj.details = [];
                    window.sessionStorage.removeItem("giftItem");
                }
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);
